package com.example.backblog.controller.base;

import com.example.backblog.vo.ApiResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.BeanUtils;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseController<T,D,R extends JpaRepository<T,Long>> {

    protected R baseRepository;
    public Class<T> clazz;
    public BaseController(){
        Type superclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = null;
        if (superclass instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) superclass;
            Type[] typeArray = parameterizedType.getActualTypeArguments();
            if (typeArray != null && typeArray.length > 0) {
                clazz = (Class<T>) typeArray[0];
            }
        }
    }
    @GetMapping("")
    public ApiResult get(Long id) {
        T entity =  this.baseRepository.findById(id).get();
        return ApiResult.success(entity);
    }
    @GetMapping("/all")
    public ApiResult getAll() {
        return ApiResult.success(this.baseRepository.findAll());
    }
    @PostMapping("")
    public ApiResult add(@RequestBody D dto) throws JsonProcessingException, InstantiationException, IllegalAccessException {
        T entity = clazz.newInstance();
        BeanUtils.copyProperties(dto,entity);
        return ApiResult.success(baseRepository.save(entity));
    }
    @PutMapping("")
    public ApiResult update(@RequestBody T entity) {
        return ApiResult.success(baseRepository.save(entity));
    }
    @DeleteMapping("")
    public ApiResult delete(Long id) throws JsonProcessingException {
        this.baseRepository.deleteById(id);
        return ApiResult.success("删除成功");
    }
    public abstract void setBaseRepository(R baseRepository);
}
